package com.example.myapplication.Network;

import android.util.Log;

import com.example.myapplication.Data.Scan;
import com.example.myapplication.R;

import org.json.JSONObject;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UdpListener implements Runnable {

    public  UdpListener listen(){
        int port = 13532;
        DatagramSocket socket = null;

        try{
            socket = new DatagramSocket(port);
            byte[] receiveData = new byte[1024];

            // 创建一个DatagramPacket实例，用于接收数据
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);

            while (true) {
                // 接收数据报
                socket.receive(receivePacket);

                // 读取数据报内容
                String jsonString = new String(receivePacket.getData(), 0, receivePacket.getLength());
                Log.d("udpreceiveData:", "来自 " + receivePacket.getAddress().getHostAddress() + ":" + receivePacket.getPort() + " 的消息: " + jsonString);

                // 可以在这里处理接收到的数据，或者发送响应等
                JSONObject jsonObject = new JSONObject(jsonString);
                Scan scan = Scan.decodeFromJson(jsonObject);



                // 重置DatagramPacket以便再次接收
                receivePacket.setLength(receiveData.length);
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 多线程执行
    @Override
    public void run() {
        listen();
    }
}
